package com.java110.mall.user.cmd.user;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.CmdContextUtils;
import com.java110.core.context.Environment;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.AuthenticationFactory;
import com.java110.dto.user.UserDto;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.user.UserPo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.ListUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 用户修改登陆密码
 */
@Java110Cmd(serviceCode = "user.changeUserPwd")
public class ChangeUserPwdCmd extends Cmd {
    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        Assert.jsonObjectHaveKey(reqJson, "newPwd", "请求参数中未包含newPwd 节点，请确认");
        Assert.jsonObjectHaveKey(reqJson, "oldPwd", "请求参数中未包含oldPwd 节点，请确认");
        Environment.isDevEnv();

    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {
        reqJson.put("oldPwd", AuthenticationFactory.passwdMd5(reqJson.getString("oldPwd")));
        reqJson.put("newPwd", AuthenticationFactory.passwdMd5(reqJson.getString("newPwd")));
        String userId = CmdContextUtils.getUserId(context);

        UserDto userDto = new UserDto();
        userDto.setUserId(userId);
        userDto.setPassword(reqJson.getString("oldPwd"));
        List<UserDto> userDtos = userV1InnerServiceSMOImpl.queryUsers(userDto);
        if (ListUtil.isNull(userDtos)) {
            throw new CmdException("原始密码错误");
        }
        UserPo userPo = new UserPo();
        userPo.setUserId(userId);
        userPo.setPassword(reqJson.getString("newPwd"));
        userV1InnerServiceSMOImpl.updateUser(userPo);
    }
}
